﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TwlNS {
	class SensorNode : Node {

		DateTime _sensingTime;
		Random random;

		public bool CanRoute {
			get {
				foreach (Node n in _ParentNodes) {
					if (n.Energy > 0)
						return true;
				}
				return false;
			}
		}

		public SensorNode() {
			_HopCount = int.MaxValue;
			_Energy = Node.InitialEnergy;
			random = new Random(Environment.RandomVariableSeed*Id);
			ReceivedMsg = false;
		}
		public override void Initialization() {
			int rand = random.Next(20) + 1;
			_sensingTime = DateTime.Now.AddSeconds(rand);
			ReceivedMsg = false;
		}

		public override void Pulse() {
			if (_sensingTime != null && DateTime.Now >= _sensingTime) {
				_Energy -= Node.SendingEnergyCost + Node.ProcessingEnergyCost + Node.SensingEnergyCost;
				int i = random.Next(_ParentNodes.Count);
				Node parent = _ParentNodes[i];
                bool packetDelayed = false;
                if (parent is SensorNode)
                {
                    if (parent.ReceivedMsg)
                    {
                        double ratio = (double)Properties.Settings.Default.CollisionDropRate;
                        double rand_Value = (new Random()).NextDouble();
                        if (rand_Value > ratio)
                            packetDelayed = true;
                    }
                    else
                    {
                        parent.ReceivedMsg = true;
                        Environment.NumInitPackets++;
                    }
                }
                else if (parent is SinkNode && !packetDelayed)
                    Environment.NumSuccessPackets++;
				
                if (packetDelayed)
                    _sensingTime = DateTime.Now;
                else
                {
                    int rand = random.Next(120) + 1;
                    _sensingTime = DateTime.Now.AddSeconds(rand);
                    
                }
			}
			if (ReceivedMsg) {
				_Energy -= Node.SendingEnergyCost + Node.ProcessingEnergyCost + Node.ReceivingEnergyCost;
				int i = random.Next(_ParentNodes.Count);
				Node parent = _ParentNodes[i];
				if (parent is SensorNode)
					parent.ReceivedMsg = true;
				else if (parent is SinkNode)
					Environment.NumSuccessPackets++;
				ReceivedMsg = false;
			}
		}


	}
}
